import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store/index'

// 路由地址权限
import asyncRouterMap from './async'

Vue.use(Router)
export {
    asyncRouterMap
}

export const constantRouterMap = [{
    path: '/',
    name: 'Layout',
    redirect: '',
    component: () =>
        import ('@/views/layout/index'),
    children: [],
    meta: { noCache: false, noRoot: true  }
}, {
    path: '/404',
    name: '404',
    component: () =>
        import ('@/views/redirect/404'),
        meta: { noCache: false, noLog: true, noRoot: true  }
}, {
    path: '/401',
    name: '401',
    component: () =>
        import ('@/views/redirect/401'),
        meta: { noCache: false, noLog: true, noRoot: true  }
}, {
    path: '/login',
    name: 'login',
    component: () =>
        import ('@/views/login'),
    meta: { noCache: false, noLog: true, noRoot: true  }
}, {
    path: '*',
    redirect: '/404'
}]

const myRouterMap = constantRouterMap

// 索引使用母版页界面 关联
asyncRouterMap.forEach(function(map) {
    myRouterMap[0].children.push(map)
})


// export const routerMap = myRouterMap

const router = new Router({
    // 打包 调整模式  缺点  路由会出现 #
    mode: 'hash',
    //     mode:'history', //去掉页面路径#美化
    routes: myRouterMap
})

// 切换路由开始  =>验证是否登录
router.beforeEach((to, from, next) => {
    //需要验证权限
    if (!to.meta.noRoot) {
        let root = false;
        let path = '';
        // to.path.replace(/\//g, '')
        if (to.meta.parentPath) {
            path = to.meta.parentPath.replace(/\//g, '')
        }
        //验证父级路由
        path = `/${path}/`;
        if (store.getters.rootUrl.indexOf(path)) {
            root = true;
        }

        //验证当前路由
        path = to.path.replace(/\//g, '')
        path = `/${path}/`;
        if (store.getters.rootUrl.indexOf(path)) {
            root = true;
        }

        if (!root) {
            // 权限不足
            next({ path: '/401' })
            return
        }
    }

    // 需要验证登录权限
    if (!to.meta.noLog) {
        // // 对路由进行验证
        if (!store.getters.isLog) {
            // 未登录则跳转到登陆界面
            next({ path: '/login' })
            return
        }
    }
    // 跳转界面
    next()
})


// 切换路由结束
router.afterEach((to, from) => {
})
  
//切换路由失败
router.onError((error) => {
    const pattern = /Loading chunk (\d)+ failed/g
    const isChunkLoadFailed = error.message.match(pattern)
    const targetPath = router.history.pending.fullPath
    console.log(error.message)
    console.log(targetPath)
    if (isChunkLoadFailed) {
      window.location.replace(window.location.href)
      //  router.replace(targetPath);
    }
  })

export default  router